package com.imooc.luckymoney.service;

import com.imooc.luckymoney.entity.Luckymoney;
import com.imooc.luckymoney.enums.ResultEnum;
import com.imooc.luckymoney.exception.LuckymoneyException;
import com.imooc.luckymoney.repository.LuckymoneyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class LuckymoneyService {
    @Autowired
    private LuckymoneyRepository repository;

    /**
     * 事务 指数据库事务
     * 扣库存 > 创建订单
     */
    @Transactional
    public void createTwo() {
        Luckymoney luckymoney1 = new Luckymoney();
        luckymoney1.setProducer("廖师兄");
        luckymoney1.setMoney(new BigDecimal("520"));
        repository.save(luckymoney1);

        Luckymoney luckymoney2 = new Luckymoney();
        luckymoney2.setProducer("廖师兄");
        luckymoney2.setMoney(new BigDecimal("1314"));
        repository.save(luckymoney2);
    }

    /**
     * 统一异常处理
     * @param id
     * @throws Exception
     */
    public void getAmount(Integer id) throws Exception{
        Luckymoney luckymoney = repository.findById(id).get();
        BigDecimal amount = luckymoney.getMoney();
        if (amount.compareTo(new BigDecimal(5)) < 0){
            throw new LuckymoneyException(ResultEnum.LESS_THAN_FIVE);
        }else if (amount.compareTo(new BigDecimal(100)) > 0){
            throw new LuckymoneyException(ResultEnum.MORE_THAN_100);
        }
        else
            throw new LuckymoneyException(ResultEnum.OTHERS);
    }

    /**
     * 测试service的例子
     * 查询一个红包的金额
     * @param id
     * @return
     */
    public BigDecimal getMoney(Integer id){
        Luckymoney luckymoney = repository.findById(id).get();
        BigDecimal money = luckymoney.getMoney();
        return money;
    }
}
